package cn.lds.healthexamspringboot.controller;

import cn.lds.healthexamspringboot.domain.User;
import cn.lds.healthexamspringboot.dto.ResponseDTO;
import cn.lds.healthexamspringboot.exception.SysException;
import cn.lds.healthexamspringboot.service.UserService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("login")
    public String login(HttpSession session,Model model){

        Object loginUser = session.getAttribute("login");

        if (Objects.nonNull(loginUser)){
            model.addAttribute("err","您已经登录，请注销后操作");
            return "index";
        }

        return "login";
    }

    @PostMapping("do_login")
    public String doLogin(User user, Model model, HttpSession session) throws SysException {

        ResponseDTO<User> userResponseDTO = userService.loginUser(user);

        if (!userResponseDTO.getCode().equals(200)){
            //错误信息放入model，其实是放入request作用域
            model.addAttribute("err",userResponseDTO.getMsg());
            return "/login";
        }
        session.setAttribute("login",userResponseDTO.getData());

        return "redirect:/";

    }
    @GetMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("login");
        return "index";
    }

    @GetMapping("register")
    public String reg(){
        return "reg";
    }

    @PostMapping("do_reg")
    public String do_reg(User user) throws SysException {

        ResponseDTO responseDTO = userService.regUser(user);

        return "login";


    }
}
